package com.jeesite.modules.task.query.service;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.jeesite.common.entity.Page;
import com.jeesite.common.io.FileUtils;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.modules.common.service.SysOfficeUnitService;
import com.jeesite.modules.sys.utils.DictUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.task.action.dao.DcSupTaskActionDao;
import com.jeesite.modules.task.action.entity.DcSupTaskAction;
import com.jeesite.modules.task.arrange.entity.DcSupTaskInfoArrange;
import com.jeesite.modules.task.deploy.dao.DcSupTaskInfoDao;
import com.jeesite.modules.task.deploy.dao.DcSupTaskInfoRefineDao;
import com.jeesite.modules.task.deploy.entity.DcSupTaskInfo;
import com.jeesite.modules.task.deploy.entity.DcSupTaskInfoRefine;
import com.jeesite.modules.task.feedback.dao.DcSupTaskFeedbackDao;
import com.jeesite.modules.task.feedback.entity.DcSupTaskFeedback;
import com.jeesite.modules.task.query.dao.ComPreHenceQueryDao;
import com.jeesite.modules.task.query.entity.ComPreHencePiShiExport;
import com.jeesite.modules.task.query.entity.ComPreHenceQueryEntity;
import com.jeesite.modules.task.query.entity.ComPreHenceQueryExport;
import com.jeesite.modules.task.query.entity.ComPreHenceQuerySuperEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ComPreHenceQueryService {

    final private ComPreHenceQueryDao comPreHenceQueryDao;

    @Autowired
    private SysOfficeUnitService sysOfficeUnitService;

    @Autowired
    private DcSupTaskInfoDao dcSupTaskInfoDao;
    @Autowired
    private DcSupTaskInfoRefineDao dcSupTaskInfoRefineDao;
    @Autowired
    private DcSupTaskActionDao dcSupTaskActionDao;
    @Autowired
    private DcSupTaskFeedbackDao dcSupTaskFeedbackDao;

    public Page<ComPreHenceQueryEntity> findComPreHencePage(ComPreHenceQueryEntity queryEntity) {
        //获取当前人user和所在机构code作为查询限制条件
        queryEntity.setOfficeCode(sysOfficeUnitService.getLatestUnitByOffice().getOfficeCode());
        queryEntity.setUserCode(UserUtils.getUser().getUserCode());

        //查询INFO主表 返回
        List<ComPreHenceQueryEntity> list = comPreHenceQueryDao.findComPreHencePage(queryEntity);
        return queryEntity.getPage().setList(list);
    }

    /**
     * 导出任务
     * @param queryEntity
     * @param request
     * @param response
     */
    public void exportData(ComPreHenceQueryEntity queryEntity, HttpServletRequest request, HttpServletResponse response){
        // 定义默认的导出文件名
        String fileName = "综合查询" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";

        // 关闭分页
        queryEntity.setPage(null);

        // 获取当前人user和所在机构code作为查询限制条件
        queryEntity.setOfficeCode(sysOfficeUnitService.getLatestUnitByOffice().getOfficeCode());
        queryEntity.setUserCode(UserUtils.getUser().getUserCode());

        // 查询 Info主表数据
        List<ComPreHenceQueryExport> list = comPreHenceQueryDao.findComPreHenceListAndExport(queryEntity);
        // 遍历补充其他数据
        list.forEach(x->{
            x.setTaskTypeCode(DictUtils.getDictLabel("dc_task_type",x.getTaskTypeCode(),""));
            x.setTaskStatus(DictUtils.getDictLabel("dc_task_status",x.getTaskStatus(),""));
            if (!x.getArranges().isEmpty()){
                // 获取整理信息 并且时间倒序 取第一个
                DcSupTaskInfoArrange arrange=x.getArranges().stream().filter(a->a.getArrangeStatus()!=null).filter(a->a.getArrangeTime()!=null).filter(a->a.getArrangeStatus().equals("2")).sorted(Comparator.comparing(DcSupTaskInfoArrange::getArrangeTime).reversed()).findFirst().orElse(new DcSupTaskInfoArrange());
                x.setArrangeStr(arrange.getArrangeContent());
            }
            StringBuffer stringBuffer = new StringBuffer();
            if (!x.getFeedbacks().isEmpty()){
                // 获取反馈数据 并且设置范围状态为7||9
                x.getFeedbacks().stream().filter(f->f.getFeedbackStatus()!=null).filter(f->f.getFeedbackStatus().equals("7")||f.getFeedbackStatus().equals("9")).forEach(f->{
                    stringBuffer.append(DateUtils.formatDate(f.getFeedbackTime(),"yyyy-MM-dd HH:mm") +"  " + "[" + f.getLeaderOrgName() + "-反馈]"+ f.getFeedbackContent()+"\n");
                });
                x.setFeedbackStr(stringBuffer.toString());
            }
        });

        try (ExcelExport ee = new ExcelExport("综合查询", ComPreHenceQueryExport.class)) {
            ee.setDataList(list).write(response, fileName);
        }
    }

    public void changeSortNum(String taskId, String sortNum){
        comPreHenceQueryDao.changeSortNum(taskId, sortNum);
    }

    public List<ComPreHenceQueryExport> findComPreHenceListAndExport(ComPreHenceQueryEntity queryEntity) {
        // 关闭分页
        queryEntity.setPage(null);

        // 获取当前人user和所在机构code作为查询限制条件
        queryEntity.setOfficeCode(sysOfficeUnitService.getLatestUnitByOffice().getOfficeCode());
        queryEntity.setUserCode(UserUtils.getUser().getUserCode());

        // 查询 Info主表数据
        List<ComPreHenceQueryExport> list = comPreHenceQueryDao.findComPreHenceListAndExport(queryEntity);
        // 遍历补充其他数据
        list.forEach(x->{
            x.setTaskStatus(DictUtils.getDictLabel("dc_task_status",x.getTaskStatus(),""));
            if (!x.getArranges().isEmpty()){
                // 获取整理信息 并且时间倒序 取第一个
                DcSupTaskInfoArrange arrange=x.getArranges().stream().filter(a->a.getArrangeStatus()!=null).filter(a->a.getArrangeTime()!=null).filter(a->a.getArrangeStatus().equals("2")).sorted(Comparator.comparing(DcSupTaskInfoArrange::getArrangeTime).reversed()).findFirst().orElse(new DcSupTaskInfoArrange());
                x.setArrangeStr(arrange.getArrangeContent());
            }
            StringBuffer stringBuffer = new StringBuffer();
            if (!x.getFeedbacks().isEmpty()){
                // 获取反馈数据 并且设置范围状态为7||9
                x.getFeedbacks().stream().filter(f->f.getFeedbackStatus()!=null).filter(f->f.getFeedbackStatus().equals("7")||f.getFeedbackStatus().equals("9")).forEach(f->{
                    stringBuffer.append(DateUtils.formatDate(f.getFeedbackTime(),"yyyy-MM-dd HH:mm") +"  " + "[" + f.getLeaderOrgName() + "-反馈]"+ f.getFeedbackContent()+"\n");
                });
                x.setFeedbackStr(stringBuffer.toString());
            }
        });
        return list;
    }

    /**
     * 导出细化分解excel
     * @param queryEntity
     * @param request
     * @param response
     */
    public void exportRefineExcel(ComPreHenceQueryEntity queryEntity, HttpServletRequest request, HttpServletResponse response) {
        List<List<String>> rows = new ArrayList<>();
        // 最大反馈次数
        int maxFeedbacks = 0;
        // 任务数据
        DcSupTaskInfo dcSupTaskInfo = new DcSupTaskInfo();
        dcSupTaskInfo.setNormalFlag("3");
        dcSupTaskInfo.setTaskYear(queryEntity.getTaskYear());
        dcSupTaskInfo.setTaskTitle(queryEntity.getTaskTitle());
        dcSupTaskInfo.setTaskTypeCode(queryEntity.getTaskTypeCode());
        List<DcSupTaskInfo> taskInfoList = dcSupTaskInfoDao.findListPage(dcSupTaskInfo);
        List<Map<String, String>> mergeList = new ArrayList<>();
        for (int i = 0; i < taskInfoList.size(); i++) {
            DcSupTaskInfo taskInfo = taskInfoList.get(i);
            // 任务分解数据
            DcSupTaskInfoRefine taskInfoRefine = new DcSupTaskInfoRefine();
            taskInfoRefine.setTaskId(taskInfo.getId());
            List<DcSupTaskInfoRefine> refineList = dcSupTaskInfoRefineDao.findList(taskInfoRefine);
            for (int j = 0; j < refineList.size(); j++) {
                DcSupTaskInfoRefine refine = refineList.get(j);
                // 表格行数据
                List<String> row = new ArrayList<>();
                // 序号
                row.add((i + 1) + "");
                // 工作任务
                row.add(taskInfo.getTaskContent());
                // 牵头责任单位
                row.add(refine.getTaskLeaderOrgName());
                // 分解到每个单位的任务发布数据
                DcSupTaskAction dcSupTaskAction = new DcSupTaskAction();
                dcSupTaskAction.setTaskId(refine.getTaskId());
                dcSupTaskAction.setLeaderOrgCode(refine.getTaskLeaderOrg());
                dcSupTaskAction = dcSupTaskActionDao.getByEntity(dcSupTaskAction);
                if (dcSupTaskAction != null) {
                    // 任务发布对应的多条反馈数据
                    DcSupTaskFeedback dcSupTaskFeedback = new DcSupTaskFeedback();
                    dcSupTaskFeedback.setActionId(dcSupTaskAction.getId());
                    dcSupTaskFeedback.getSqlMap().getOrder().setOrderBy("feedback_start_time asc, feedback_end_time asc");
                    List<DcSupTaskFeedback> feedbackList = dcSupTaskFeedbackDao.findList(dcSupTaskFeedback);
                    if (feedbackList.size() > maxFeedbacks) {
                        maxFeedbacks = feedbackList.size();
                    }
                    for (int k = 0; k < feedbackList.size(); k++) {
                        DcSupTaskFeedback feedback = feedbackList.get(k);
                        // 阶段起止时间
                        row.add(DateUtils.formatDate(feedback.getFeedbackStartTime(), "yyyy-MM-dd hh:ss") + "至" + DateUtils.formatDate(feedback.getFeedbackEndTime()));
                        // 阶段目标任务
                        row.add(feedback.getFeedbackRequire());
                        String feedbackTime = "";
                        String feedbackContent = "";
                        if (StringUtils.isNotBlank(feedback.getFeedbackContent())) {
                            feedbackTime = DateUtils.formatDate(feedback.getFeedbackTime(), "yyyy-MM-dd hh:ss");
                            feedbackContent = feedback.getFeedbackContent();
                        }
                        // 阶段反馈时间
                        row.add(feedbackTime);
                        // 阶段目标完成情况
                        row.add(feedbackContent);
                    }
                }
                rows.add(row);
            }
            if (refineList.size() > 1) {
                Map<String, String> mergeMap = new HashMap<>();
                mergeMap.put("firstRow", (rows.size() - refineList.size() + 1) + "");
                mergeMap.put("lastRow", rows.size() + "");
                mergeMap.put("content1", rows.get(rows.size() - 1).get(0));
                mergeMap.put("content2", taskInfo.getTaskContent());
                mergeList.add(mergeMap);
            }
        }

        String fileName = "细化分解任务" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";

        ExcelWriter writer = ExcelUtil.getWriter(fileName);
        // 表头行
        List<String> headerRow = new ArrayList<>();
        headerRow.add("序号");
        headerRow.add("工作任务");
        headerRow.add("牵头责任单位");
        for (int i = 1; i <= maxFeedbacks; i++) {
            headerRow.add("第" + i + "阶段起止时间");
            headerRow.add("第" + i + "阶段目标任务");
            headerRow.add("第" + i + "阶段反馈时间");
            headerRow.add("第" + i + "阶段目标完成情况");
        }
        // 没有数据的单元格，填充占位符，保持表格整体样式
        rows.forEach(row -> {
            if (row.size() < headerRow.size()) {
                int cells = headerRow.size() - row.size();
                for (int i = 0; i < cells; i++) {
                    row.add("");
                }
            }
        });
        // 一次性写出内容，强制输出标题
        writer.writeHeadRow(headerRow);
        for (int i = 0; i < headerRow.size(); i++) {
            writer.setColumnWidth(i, headerRow.get(i).getBytes().length);
        }
        writer.write(rows, true);
        mergeList.forEach(merge -> {
            writer.merge(Integer.valueOf(merge.get("firstRow")), Integer.valueOf(merge.get("lastRow")), 0, 0, merge.get("content1"), false);
            writer.merge(Integer.valueOf(merge.get("firstRow")), Integer.valueOf(merge.get("lastRow")), 1, 1, merge.get("content2"), false);
        });
        for (int i = 0; i < headerRow.size(); i++) {
            // 调整每一列宽度
            writer.getSheet().setColumnWidth(i,10000);
        }

        // 关闭writer，释放内存
        writer.close();

        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        String tempFile = path + fileName;
        FileUtils.downFile(new File(tempFile), request, response, fileName);
        FileUtils.deleteFile(tempFile);

    }


    public void exportRefineExcelNew(ComPreHenceQueryEntity queryEntity, HttpServletRequest request, HttpServletResponse response){
        List<List<String>> rows = new ArrayList<>();
        int maxFeedbacks = 0;
        DcSupTaskInfo dcSupTaskInfo = new DcSupTaskInfo();
        dcSupTaskInfo.setNormalFlag("3");
        dcSupTaskInfo.setTaskYear(queryEntity.getTaskYear());
        dcSupTaskInfo.setTaskTitle(queryEntity.getTaskTitle());
        dcSupTaskInfo.setTaskTypeCode(queryEntity.getTaskTypeCode());
        List<Map<String, String>> mergeList = new ArrayList<>();
        List<ComPreHenceQuerySuperEntity> superEntities =  comPreHenceQueryDao.exportRefineExcelNew(dcSupTaskInfo);
        System.out.println(superEntities);

        for (int i = 0; i < superEntities.size(); i++) {
            final ComPreHenceQuerySuperEntity superEntity = superEntities.get(i);
            for (DcSupTaskInfoRefine dcSupTaskInfoRefine : superEntity.getDcSupTaskInfoRefines()) {
                List<String> row = new ArrayList<>();
                // 序号
                row.add((i + 1) + "");
                // 工作任务
                row.add(superEntity.getDcSupTaskInfo().getTaskContent());
                // 牵头责任单位
                row.add(dcSupTaskInfoRefine.getTaskLeaderOrgName());
                final String taskLeaderOrg = dcSupTaskInfoRefine.getTaskLeaderOrg();
                final String taskId = dcSupTaskInfoRefine.getTaskId();
//                dcSupTaskFeedback.getSqlMap().getOrder().setOrderBy("feedback_start_time asc, feedback_end_time asc");

                final List<DcSupTaskFeedback> feedbackList = superEntity.getDcSupTaskFeedbacks().stream().filter(x -> StringUtils.equals(taskLeaderOrg,x.getLeaderOrgCode()) && StringUtils.equals(taskId,x.getTaskId())).sorted(Comparator.comparing(DcSupTaskFeedback::getFeedbackStartTime)).collect(Collectors.toList());
                if (feedbackList.size() > maxFeedbacks) {
                    maxFeedbacks = feedbackList.size();
                }
                for (int k = 0; k < feedbackList.size(); k++) {
                    DcSupTaskFeedback feedback = feedbackList.get(k);
                    // 阶段起止时间
                    row.add(DateUtils.formatDate(feedback.getFeedbackStartTime(), "yyyy-MM-dd hh:ss") + "至" + DateUtils.formatDate(feedback.getFeedbackEndTime()));
                    // 阶段目标任务
                    row.add(feedback.getFeedbackRequire());
                    String feedbackTime = "";
                    String feedbackContent = "";
                    if (StringUtils.isNotBlank(feedback.getFeedbackContent())) {
                        feedbackTime = DateUtils.formatDate(feedback.getFeedbackTime(), "yyyy-MM-dd hh:ss");
                        feedbackContent = feedback.getFeedbackContent();
                    }
                    // 阶段反馈时间
                    row.add(feedbackTime);
                    // 阶段目标完成情况
                    row.add(feedbackContent);
                }
                rows.add(row);
            }

            if (superEntity.getDcSupTaskInfoRefines().size() > 1) {
                Map<String, String> mergeMap = new HashMap<>();
                mergeMap.put("firstRow", (rows.size() - superEntity.getDcSupTaskInfoRefines().size() + 1) + "");
                mergeMap.put("lastRow", rows.size() + "");
                mergeMap.put("content1", rows.get(rows.size() - 1).get(0));
                mergeMap.put("content2", superEntity.getDcSupTaskInfo().getTaskContent());
                mergeList.add(mergeMap);
            }
        }
        String fileName = "细化分解任务" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";

        ExcelWriter writer = ExcelUtil.getWriter(fileName);
        // 表头行
        List<String> headerRow = new ArrayList<>();
        headerRow.add("序号");
        headerRow.add("工作任务");
        headerRow.add("牵头责任单位");
        for (int i = 1; i <= maxFeedbacks; i++) {
            headerRow.add("第" + i + "阶段起止时间");
            headerRow.add("第" + i + "阶段目标任务");
            headerRow.add("第" + i + "阶段反馈时间");
            headerRow.add("第" + i + "阶段目标完成情况");
        }
        // 没有数据的单元格，填充占位符，保持表格整体样式
        rows.forEach(row -> {
            if (row.size() < headerRow.size()) {
                int cells = headerRow.size() - row.size();
                for (int i = 0; i < cells; i++) {
                    row.add("");
                }
            }
        });
        // 一次性写出内容，强制输出标题
        writer.writeHeadRow(headerRow);
        for (int i = 0; i < headerRow.size(); i++) {
            writer.setColumnWidth(i, headerRow.get(i).getBytes().length);
        }
        writer.write(rows, true);
        mergeList.forEach(merge -> {
            writer.merge(Integer.valueOf(merge.get("firstRow")), Integer.valueOf(merge.get("lastRow")), 0, 0, merge.get("content1"), false);
            writer.merge(Integer.valueOf(merge.get("firstRow")), Integer.valueOf(merge.get("lastRow")), 1, 1, merge.get("content2"), false);
        });
        for (int i = 0; i < headerRow.size(); i++) {
            // 调整每一列宽度
            writer.getSheet().setColumnWidth(i,10000);
        }

        // 关闭writer，释放内存
        writer.close();

        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        String tempFile = path + fileName;
        FileUtils.downFile(new File(tempFile), request, response, fileName);
        FileUtils.deleteFile(tempFile);
    }

    public void btnExportPiShi(ComPreHenceQueryEntity queryEntity, HttpServletRequest request, HttpServletResponse response) {
        //获取当前人user和所在机构code作为查询限制条件
        queryEntity.setOfficeCode(sysOfficeUnitService.getLatestUnitByOffice().getOfficeCode());
        queryEntity.setUserCode(UserUtils.getUser().getUserCode());
        List<ComPreHencePiShiExport> list = comPreHenceQueryDao.btnExportPiShi(queryEntity);
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i)!=null){
                list.get(i).setSortNumber(i+1);
            }
        }
        String fileName = "批示导出" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
        try(ExcelExport ee = new ExcelExport("批示导出", ComPreHencePiShiExport.class)){
            ee.setDataList(list).write(response, fileName);
        }
    }
}
